<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Business, Opend};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function getlatlon()
    {
        $id = $this->request->user_id;
        $startime = strtotime(date('Y-m-d'));
        $getlats = Redis::zRangeByScore('getlatlonarrs' . $id, $startime, time());
        $lists = [];
        $getlats = array_unique($getlats);
        foreach ($getlats as $k => &$getlat) {
            $time = Redis::zScore('getlatlonarrs' . $id, $getlat) ?? 0;
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $text = '未知地址';
            $res = api_curl($url, ['location' => $getlat, 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'all']);
            if (!empty($res['regeocode']['formatted_address'])) {
                $text = $res['regeocode']['formatted_address'];
            }
            if (!empty($res['regeocode']['aois'][0]['name'])) {
                $text = $res['regeocode']['aois'][0]['name'];
            }
            $getlat = explode(',', $getlat);
            if (count($getlat) < 2 || $getlat[0] == 'undefined') {
                unset($getlats[$k]);
            }
            $lists[] = [
                'latitude' => $getlat[1],
                'longitude' => $getlat[0],
                'desc' => date('Y-m-d H:i:s', $time),
                'title' => $text
            ];
        }
        //$getlats = array_values($getlats);
        $this->result($lists, 0, '操作成功');
    }

    public function other()
    {
        $statuslist = [
            ['id' => 1, 'name' => '营业中'],
            ['id' => 2, 'name' => '预备开业'],
            ['id' => 3, 'name' => '可选店面'],
        ];
        $firstlist = [
            ['id' => 1, 'name' => '首单未发货'],
            ['id' => 2, 'name' => '首单已发货']
        ];
        $huolist = [
            ['id' => 1, 'name' => '货架未发货'],
            ['id' => 2, 'name' => '货架已发货']
        ];
        $type = config('config.type');
        $typelist = [];
        foreach ($type as $k => $v) {
            if ($k != 1) {
                $typelist[] = ['id' => $k, 'name' => $v];
            }
        }
        $people = (new Users())->where(['type' => 3, 'del' => 1])->field('id,account as name')->select();
        $this->result(['firstlist' => $firstlist, 'statuslist' => $statuslist, 'typelist' => $typelist, 'people' => $people, 'huolist' => $huolist], 0, '获取成功');
    }

    public function login()
    {
        $data = $this->request->post();
        Log::write($data, 'test');
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require',
        ], [
            'mobile.require' => '登陆账号不能为空',
            'password.require' => '登陆密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        //判断用户是否已经注册
        $user = $model->where('account', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在');
        }
        if ($user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号密码错误');
        }
        $token = 'user_' . md5(time() . $user['account']);
        Redis::setex($token, 7 * 86400, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }


    //业务经理添加和修改
    public function addshop()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'title' => 'require',
                'name' => 'require',
                'lat' =>  'require|gt:0',
                'lon' =>  'require|gt:0',
                'address' => 'require',
                'shouhou' => 'require',
            ], [
                'type.require' => '类型不能为空',
                'type.in' => '类型错误',
                'title.require' => '店铺名称不能为空',
                'name.require' => '店铺联系人不能为空',
                'lat.require' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
                'lat.gt' => '坐标参数错误',
                'lon.gt' => '坐标参数错误',
                'address.require' => '详细地址不能为空',
                'shouhou.require' => '售后人员不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }

            if ($this->request->user['type'] != 1) {
                $this->result([], 1, '您不是业务经理，无权操作此项');
            }
            $shouhou = (new Users())->where(['id' => $data['shouhou'], 'del' => 1])->find();
            if (empty($shouhou)) {
                $this->result([], 1, '售后经理不存在');
            }
            $data['suid'] = $shouhou['id'];
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $data['province'] = $result['result']['ad_info']['province'] ?? '';
                $data['city'] = $result['result']['ad_info']['city'] ?? '';
                $data['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                return json(['code' => 1, 'data' => [], 'msg' =>  $e->getMessage()]);
            }
            $data['user_id'] = $this->request->user_id;
            $data['yuid'] = $this->request->user_id;
            $data['times'] = date('Y-m-d');
            $model = new Business();
            if (!empty($data['id'])) {
                $shoplist = (new Business())->where(['yuid' => $this->request->user_id, 'id' => $data['id']])->find();
                if (empty($shoplist)) {
                    $this->result([], 1, '信息错误，请重试');
                }
                $data['type'] = $shoplist['type'];
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $data = $this->request->get();
            $lat = (float)$this->request->get('lat', 0) ?? 0;
            $lng = (float)$this->request->get('lng', 0) ?? 0;
            if (!empty($lat) && !empty($lng)) {
                if ($lat != 'undefined' && $lng != 'undefined') {
                    Redis::zAdd('getlatlonarrs' . $this->request->user_id, time(), $lng . ',' . $lat);
                }
            }
            $where = [];
            if ($this->request->user['type'] == 1) {
                $where[] = ['yuid', '=', $this->request->user_id];
            } elseif ($this->request->user['type'] == 2) {
                $where[] = ['duid', '=', $this->request->user_id];
            } elseif ($this->request->user['type'] == 3) {
                $where[] = ['suid', '=', $this->request->user_id];
            } else {
                $this->result([], 0, '获取成功');
            }
            if (!empty($data['status'])) {
                $where[] = ['status', '=', $data['status']];
            }
            if (!empty($data['keywords'])) {
                $where[] = ['title|name|address|getaddress|province|city|area', 'like', '%' . $data['keywords'] . '%'];
            }
            $result = (new Business())->where($where)->order('id desc')->where(['status' => [1, 2, 3]])->select();
            $statuslist[1] = '营业中';
            $statuslist[2] = '预备开业';
            $statuslist[3] = '可选店面';
            $statuslist[4] = '店面已删除';
            $statuslist[5] = '停业';
            $first = [1 => '首单未发货', 2 => '首单已发货'];
            $huo = [1 => '货架未发货', 2 => '货架已发货'];
            foreach ($result as $shop) {
                $shop['img'] = config()["config"]['img'][$shop['type']] ?? '';
                $shop['first_name'] = $first[$shop['isfirst']] ?? '';
                $shop['huo_name'] = $huo[$shop['ishuo']] ?? '';
                $shop['type_name'] = config()["config"]['type'][$shop['type']] ?? '';
                $shop['status_name'] = $statuslist[$shop['status']] ?? '';
                $shop['shouhuo'] = (new Users())->where('id', $shop['suid'])->value('account'); //售后经理
                $shop['dudao'] = (new Users())->where('id', $shop['duid'])->value('account'); //督导
                $shop['yewu'] = (new Users())->where('id', $shop['yuid'])->value('account'); //业务经理
                $shop['images'] = json_decode($shop['images'] ?? '', true) ?? [];
            }
            $this->result(['data' => $result, 'type' => $this->request->user['type']], 0, '获取成功');
        }
    }

    //督导添加和修改
    public function addshop2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'title' => 'require',
                'images' => 'require',
                'name' => 'require',
                'lat' =>  'require|gt:0',
                'lon' =>  'require|gt:0',
                'address' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'title.require' => '店铺名称不能为空',
                'name.require' => '店铺联系人不能为空',
                'lat.require' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
                'lat.gt' => '坐标参数错误',
                'lon.gt' => '坐标参数错误',
                'images.require' => '照片不能为空',
                'address.require' => '详细地址不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }

            if ($this->request->user['type'] != 2) {
                $this->result([], 1, '您不是督导，无权操作此项');
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $data['province'] = $result['result']['ad_info']['province'] ?? '';
                $data['city'] = $result['result']['ad_info']['city'] ?? '';
                $data['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                return json(['code' => 1, 'data' => [], 'msg' =>  $e->getMessage()]);
            }
            $model = new Business();
            $shoplist = (new Business())->where(['duid' => $this->request->user_id, 'id' => $data['id']])->find();
            if (empty($shoplist)) {
                $this->result([], 1, '信息错误，请重试');
            }
            $data['images'] = json_encode($data['images'], true);
            $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }

    //售后添加和修改
    public function addshop3()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'mobile' => 'require',
                'isfirst' => 'require',
                'ishuo' =>  'require|gt:0'
            ], [
                'id.require' => 'ID不能为空',
                'mobile.require' => '收银机编码不能为空',
                'isfirst.require' => '首单状态不能为空',
                'ishuo.require' => '货架状态不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }

            if ($this->request->user['type'] != 3) {
                $this->result([], 1, '您不是售后，无权操作此项');
            }
            $model = new Business();
            $shoplist = (new Business())->where(['suid' => $this->request->user_id, 'id' => $data['id']])->find();
            if (empty($shoplist)) {
                $this->result([], 1, '信息错误，请重试');
            }
            $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }

    public function getaddress()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $title  = $this->request->get('title');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Business())
            ->field('id,type,title,name,mobile,lat,lon,province,city,area,address,getaddress,times,status,' . $filed)
            ->order('dist asc');
        if (!empty($title)) {
            $result = $result->where('title|name|mobile|province|city|area|address', 'like', '%' . $title . '%');
        }
        $result = $result->where(['status' => [1, 2, 3]])->where('type', "<>", 1)->having('dist <= 10')->select();
        foreach ($result as $shop) {
            $shop['km'] = $shop['dist'] . 'km';
            $shop['img'] = config()["config"]['img'][$shop['type']] ?? '';
            $shop['type'] = config()["config"]['type'][$shop['type']] ?? '';
            $shop['opend'] = (new Opend())->where(['businessid' => $shop['id'], 'user_id' => $this->request->user_id, 'czstatus' => 1])->find();
            if (!empty($shop['opend']) && $shop['opend']['czstatus'] == 1) {
                $shop['title'] = $shop['title'] . '[营业申请中]';
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function shoplist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'title' => 'require',
                'name' => 'require',
                'mobile' => 'require',
                'lat' =>  'require',
                'lon' =>  'require',
                'address' => 'require',
            ], [
                'type.require' => '类型不能为空',
                'type.in' => '类型错误',
                'title.require' => '店铺名称不能为空',
                'name.require' => '店铺用户不能为空',
                'mobile.require' => '收银机编码不能为空',
                'lat.require' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
                'address.require' => '详细地址不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $data['getaddress'] = $result['result']['formatted_addresses']['recommend'] ?? '';
                $data['province'] = $result['result']['ad_info']['province'] ?? '';
                $data['city'] = $result['result']['ad_info']['city'] ?? '';
                $data['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                return json(['code' => 1, 'data' => [], 'msg' =>  $e->getMessage()]);
            }
            $data['user_id'] = $this->request->user_id;
            $data['times'] = date('Y-m-d');
            $model = new Business();
            if (!empty($data['id'])) {
                $shoplist = (new Business())->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
                if (empty($shoplist)) {
                    $this->result([], 1, '信息错误，请重试');
                }
                $data['type'] = $shoplist['type'];
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $result = (new Business())->where(['user_id' => $this->request->user_id, 'status' => [1, 2, 3]])->select();
            foreach ($result as $shop) {
                $shop['img'] = config()["config"]['img'][$shop['type']] ?? '';
                $shop['type'] = config()["config"]['type'][$shop['type']] ?? '';
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function opend()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'businessid' => 'require',
            'dates' => 'require',
            'status' => 'require|in:1,2,3',
        ], [
            'businessid.require' => '店铺ID不能为空',
            'dates.require' => '开业日期不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $business = (new Business())->where(['id' => $data['businessid'], 'status' => [1, 2, 3]])->find();
        if (empty($business)) {
            $this->result([], 1, '店铺不存在或已删除');
        }
        if ($business['status'] == $data['status']) {
            $this->result([], 1, '店铺已处于申请状态');
        }
        $dates = strtotime($data['dates']);
        $data['dates'] = date('Y-m-d', $dates);
        $opend = (new Opend())->where(['businessid' => $data['businessid'], 'user_id' => $this->request->user_id, 'czstatus' => 1])->find();
        if ($opend) {
            $res =  (new Opend())->save(['businessid' => $data['businessid'], 'user_id' => $this->request->user_id, 'czstatus' => 1, 'times' => $data['dates'], 'status' => $data['status'], 'created' => date('Y-m-d H:i:s'), 'mobile' => $data['mobile']], ['id' => $opend['id']]);
        } else {
            $res =  (new Opend())->save(['businessid' => $data['businessid'], 'user_id' => $this->request->user_id, 'czstatus' => 1, 'status' => $data['status'], 'times' => $data['dates'], 'mobile' => $data['mobile']]);
        }
        if ($res) {
            $this->result([], 0, '提交成功,请等待审核');
        }
        $this->result([], 1, '提交失败,请重试');
    }

    public function shoplist_del()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $model = new Business();
            $shoplist = (new Business())->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
            if (empty($shoplist)) {
                $this->result([], 1, '信息不存在，请重试');
            }
            $res = $model->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->update(['status' => 4]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }
}
